package stud.aistar.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alipay.api.AlipayConstants;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import stud.aistar.Handler.MyWebSocketHandler;
import stud.aistar.alipay.AlipayClient;
import stud.aistar.alipay.core.AlipayCore;
import stud.aistar.alipay.entity.request.AlipayRefundRequest;
import stud.aistar.alipay.entity.request.AlipayWebSiteRequest;
import stud.aistar.alipay.entity.response.AlipayRefundResponse;
import stud.aistar.config.AlipayConfig;
import stud.aistar.entity.Pay;
import stud.aistar.entity.RegOffice;
import stud.aistar.entity.User;
import stud.aistar.service.IOrderVoService;
import stud.aistar.service.IPayService;
import stud.aistar.service.IRegOfficeService;
import stud.aistar.service.IWorkTimeService;
import stud.aistar.util.DateUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;

/**
 * Created by Administrator on 2019/10/9.
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {

    private static final Log log= LogFactory.get();

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private IRegOfficeService regOfficeService;

    @Autowired
    private IPayService payService;

    @Autowired
    private IWorkTimeService workTimeService;

    @Autowired
    private IOrderVoService orderVoService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    public MyWebSocketHandler handler;

    @RequestMapping("/web")
    public String payInWebSite(String amt, String patient, String name, String personCard, String sex, String age, String tel,
                               String patientId, String firstdep, String seconddep, String doctor, String time,
                               ModelMap modelMap){




        if (regOfficeService.findOne(Integer.valueOf(patient),Integer.valueOf(doctor),Integer.valueOf(time))!=null){
            modelMap.addAttribute("flag",1);

            return "reg/regOffice";
        }
        if(regOfficeService.findCount(Integer.valueOf(doctor),Integer.valueOf(time))<workTimeService.findStatusByDocIdAndTimeId(
                Integer.valueOf(doctor),Integer.valueOf(time))){
            modelMap.addAttribute("flag",2);
            return "reg/regOffice";
        }

        try {
            AlipayCore.ClientBuilder clientBuilder = new AlipayCore.ClientBuilder();
            AlipayCore alipayCore = clientBuilder.setAlipayPublicKey(alipayConfig.getAlipay_public_key())
                    .setAppId(alipayConfig.getAppid())
                    .setPrivateKey(alipayConfig.getPrivate_key())
                    .setSignType(AlipayConstants.SIGN_TYPE_RSA2).build();

            AlipayWebSiteRequest request = new AlipayWebSiteRequest();


//
//            处理中文乱码
            name= URLEncoder.encode(name,"UTF-8");
            sex= URLEncoder.encode(sex,"UTF-8");


//          同步处理地址
            request.setReturnUrl("http://localhost:8888/treatment/alipay/alipay_sync_web?amt="+amt+"&patient="+patient+"&name="+name+"" +
                    "&personCard="+personCard+"&sex="+sex+"&age="+age+"&tel="+tel+"&patientId="+patientId+"&firstdep="+firstdep+"&seconddep="+seconddep+"&doctor="+doctor+"&time="+time);

            AlipayWebSiteRequest.BizContent bizContent = new AlipayWebSiteRequest.BizContent();
            bizContent.setTotalAmount(amt);
            bizContent.setSubject("知医治电脑网站支付");
            bizContent.setBody("测试");
            bizContent.setOutTradeNo(System.currentTimeMillis()+"1000");
            request.setBizContent(bizContent);
            String html = AlipayClient.payInWebSite(request,alipayCore);

            modelMap.addAttribute("form", html);

        } catch (Exception e) {
            log.error("电脑网站支付失败",e);
        }

        return "alipay/pay";
    }

    @RequestMapping("/alipay_sync_web")
    public String sync_web(HttpServletRequest request){
//创建对象
        RegOffice regOffice =new RegOffice();
        Pay pay = new Pay();
        Enumeration<String> its = request.getParameterNames();
        while (its.hasMoreElements()){
            String name = its.nextElement();
            String value = request.getParameter(name);

            try {
                value=URLDecoder.decode(value,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

//根据key取出value并且封装
            switch (name){
                case "amt" :
                    regOffice.setRegPrice(Double.valueOf(value));
                    pay.setAmt(Double.valueOf(value));
                    break;
                case "name" :
                    regOffice.setPatientName(value);
                    break;
                case "tel":
                    regOffice.setPatientTel(value);
                    break;
                case "personCard":
                    regOffice.setPersonCard(value);
                    break;
                case "sex":
                    regOffice.setPatientSex(value);
                    break;
                case "age":
                    regOffice.setPatientAge(Integer.valueOf(value));
                    break;
                case "patientId":
                    regOffice.setPatientCard(value);
                    break;
                case "firstdep":
                    regOffice.setFirstdepartmentId(Integer.valueOf(value));
                    break;
                case "seconddep":
                    regOffice.setSeconddepartmentsId(Integer.valueOf(value));
                    break;
                case "doctor":
                    regOffice.setDoctorId(Integer.valueOf(value));
                    break;
                case "time":
                    regOffice.setTimeId(Integer.valueOf(value));
                    break;
                case "patient":
                    regOffice.setPatientId(Integer.valueOf(value));
                    break;
                case "out_trade_no":
                    pay.setOutTradeNo(value);
                    break;
            }

            //log.info(name+"="+value);
        }
        regOffice.setCreateTime(DateUtil.getCurrentTime());
        regOffice.setRegStatus(0);
        User user = (User) request.getSession().getAttribute("user");
        regOffice.setUserId(user.getId());
        //System.out.println(regOffice);
        regOfficeService.saveReg(regOffice);

        RegOffice breg=regOfficeService.findOne(regOffice.getPatientId(),regOffice.getDoctorId(),regOffice.getTimeId());

        pay.setCreateTime(DateUtil.getCurrentTime());
        pay.setRegId(breg.getId());
        payService.savePay(pay);
        return "redirect:/alipay/send";
    }

    @RequestMapping("/send")
    public String SennerMsg(){
        String msg = "你有新的预约";
        amqpTemplate.convertAndSend("exchange","a",msg);
        return "redirect:/personal/user";
    }

    @RabbitListener(queues = "queue")
    @ResponseBody
    public void Recive(String msg) throws Exception{
        handler.sendMsgToJsp(new TextMessage(msg), "A");
    }

    @RequestMapping(value = "/refund",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object refund(String amt, String outTradeNo,String Oid){

        orderVoService.updateByOId(Integer.valueOf(Oid));

        try {
            AlipayCore.ClientBuilder clientBuilder = new AlipayCore.ClientBuilder();
            AlipayCore alipayCore = clientBuilder.setAlipayPublicKey(alipayConfig.getAlipay_public_key())
                    .setAppId(alipayConfig.getAppid())
                    .setPrivateKey(alipayConfig.getPrivate_key())
                    .setSignType(AlipayConstants.SIGN_TYPE_RSA2).build();

            AlipayRefundRequest request = new AlipayRefundRequest();
            request.setOutTradeNo(outTradeNo);
            request.setRefundAmount(amt);
            request.setRefundReason("知医治退款");
            request.setOutRequestNo(System.currentTimeMillis() + "");
            AlipayRefundResponse response = AlipayClient.refund(request, alipayCore);
            return response;
        } catch (Exception e) {
            log.error("支付宝退款失败.",e);
            return e;
        }
    }
}
